document.addEventListener('DOMContentLoaded', function() {
	// 从localStorage中获取菜单数据
	const storedMenus = localStorage.getItem('menus');
	if (storedMenus) {
		const menus = JSON.parse(storedMenus);
		const menuContainer = document.getElementById('menu-container');

		// 动态生成菜单
		function generateMenu(menus, parent) {
			menus.forEach(menu => {
				const menuItem = document.createElement('li');
				menuItem.className = 'accordion-item';

				// 为每个菜单项添加唯一类名
				if (menu.id === 'course-audit') { // 假设课程审核的ID是002-001
					menuItem.classList.add('course-audit-menu');
				}


				const header = document.createElement('a');
				header.href = '#';
				header.className = 'accordion-header';

				// 添加图标
				const icon = document.createElement('i');

				if (parent === menuContainer) {
					// 一级菜单 - 根据菜单ID设置不同图标
					switch (menu.id) {
						case '001':
							icon.className = 'fas fa-home'; // 首页
							break;
						case '002':
							icon.className = 'fas fa-book'; // 课程管理
							break;
						case '003':
							icon.className = 'fas fa-users'; // 用户管理
							break;
						case '004':
							icon.className = 'fas fa-shopping-cart'; // 订单管理
							break;
						case '005':
							icon.className = 'fas fa-cog'; // 系统设置
							break;
						default:
							icon.className = 'fas fa-th-large'; // 默认图标
					}
					header.style.fontSize = '16px';
					header.style.paddingLeft = '20px';
				} else {
					// 二级菜单保持不变
					icon.className = 'fas fa-circle';
					icon.style.fontSize = '8px';
					header.style.fontSize = '14px';
					header.style.paddingLeft = '40px';
					header.style.color = 'rgb(201 201 201)';
				}

				header.appendChild(icon);

				// 添加文本
				const text = document.createElement('span');
				text.textContent = ' ' + menu.mname;
				text.style.marginLeft = '10px';
				header.appendChild(text);

				header.setAttribute('data-target', menu.id);
				menuItem.appendChild(header);

				if (menu.subMenus && menu.subMenus.length > 0) {
					const subMenuList = document.createElement('ul');
					subMenuList.className = 'accordion-content';
					generateMenu(menu.subMenus, subMenuList);
					menuItem.appendChild(subMenuList);
				}

				parent.appendChild(menuItem);
			});
		}
		generateMenu(menus, menuContainer);

		// 修改点击事件处理
		document.querySelectorAll('.accordion-header').forEach(header => {
			header.addEventListener('click', function(event) {
				event.preventDefault();
				const target = this.getAttribute('data-target');
				const subMenu = this.nextElementSibling;
				const arrow = this.querySelector('.menu-arrow');

				if (subMenu && subMenu.classList.contains('accordion-content')) {
					// 切换子菜单显示状态
					const isExpanded = subMenu.style.display === 'block';
					subMenu.style.display = isExpanded ? 'none' : 'block';

					// 切换箭头方向
					if (arrow) {
						arrow.className = isExpanded ?
							'fas fa-chevron-up menu-arrow' :
							'fas fa-chevron-down menu-arrow';
					}
				}

				// 切换内容显示
				switchContent(target);
			});
		});

		// 默认显示第一个菜单项的内容
		switchContent('001');
		
		// 检查URL参数或本地存储，以确定是否需要显示“课程审核”内容
		const urlParams = new URLSearchParams(window.location.search);
		const activeMenuId = urlParams.get('menuId') || '001';
		if (activeMenuId === 'course-audit') {
			switchContent('course-audit');
		} else {
			switchContent(activeMenuId);
		}
	} else {
		console.error('没有找到存储在本地的菜单数据，请先登录并获取菜单数据。');
	}


// 修改发布时间的选择监听器
	const releaseDateInput = document.getElementById('release-date');
	if(releaseDateInput){
		releaseDateInput.addEventListener('change',function(){
			const selectedDate = this.value;
			console.log("选择发布的时间:",selectedDate);
			// 时间筛选函数的调用
			filterCoursesByDate(selectedDate);
		});
	}
});

// 添加时间筛选函数
function filterCoursesByDate(date) {
    console.log('正在按发布时间筛选:', date);
    
    const url = config.coursesip;
    const params = new URLSearchParams({
        method: 'queryall',
        releasedate: date || '',
        pageno: '1',
        id: '123'
    });

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        console.log('时间筛选返回数据:', data);
        if (data && Array.isArray(data.data)) {
            renderCourseTable(data.data);
        } else {
            console.error('无效的筛选结果:', data);
            renderCourseTable([]);
        }
    })
    .catch(error => {
        console.error('时间筛选失败:', error);
        renderCourseTable([]);
    });
}

// 切换内容显示的函数
function switchContent(id) {
	const contentSections = document.querySelectorAll('.content-section');
	contentSections.forEach(section => {
		section.style.display = 'none';
	});

	const targetSection = document.getElementById(id);
	if (targetSection) {
		targetSection.style.display = 'block';

		// 当切换到课程列表页面时，发送请求获取所有课程
		if (id === '002') {
			fetchAllCourses();
		}
		// 获取教师数据的函数也需要修改
		if (id === 's009') {
		    const params = new URLSearchParams({
		        method: 'getreview'
		    });
		    const url = `${config.usersip}?${params}`;
		
		    fetch(url, {
		        method: 'GET',
		        headers: {
		            'Content-Type': 'application/x-www-form-urlencoded'
		        }
		    })
		    .then(response => response.json())
		    .then(data => {
		        console.log('服务器返回的教师审核数据:', data);
		        if (data && Array.isArray(data.data)) {
		            // 更新统计卡片的数据
		            updateTeacherStats(data.data);
		            // 渲染表格
		            renderTeacherTable(data.data);
		        } else {
		            throw new Error('数据格式不正确');
		        }
		    })
		    .catch(error => {
		        console.error('获取教师审核数据失败:', error);
		        const teacherAuditContainer = document.querySelector('#s009 tbody');
		        if (teacherAuditContainer) {
		            teacherAuditContainer.innerHTML = `
		                <tr>
		                    <td colspan="7" class="error-message">
		                        获取数据失败，请稍后重试
		                        <button onclick="switchContent('s009')">重试</button>
		                    </td>
		                </tr>
		            `;
		        }
		    });
		}

		// 触发内容切换事件
		window.dispatchEvent(new CustomEvent('contentSwitch', {
			detail: {
				id: id
			}
		}));
	}
}

// 添加更新统计卡片的函数
function updateTeacherStats(teachers) {
    const pendingCount = teachers.filter(t => t.status === 'pending').length;
    const approvedCount = teachers.filter(t => t.status === 'approved').length;
    const rejectedCount = teachers.filter(t => t.status === 'rejected').length;

    document.querySelector('#s009 .status-card.pending strong').textContent = pendingCount;
    document.querySelector('#s009 .status-card.approved strong').textContent = approvedCount;
    document.querySelector('#s009 .status-card.rejected strong').textContent = rejectedCount;
}

// 定义一个变量存储所有课程数据
let allCourses = [];

// 在页面加载时获取所有课程数据
function fetchAllCourses() {
    const params = new URLSearchParams({
        method: 'queryall'
    });

    fetch(config.coursesip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data && Array.isArray(data.data)) {
            allCourses = data.data; // 保存所有课程数据
            renderCourseTable(allCourses);
        }
    })
    .catch(error => {
        console.error('获取课程数据失败:', error);
    });
}

function renderCourseTable(courses) {
	const courseListContainer1 = document.getElementById('002');
	const courseListContainer = courseListContainer1.querySelector('tbody');
	if (!courseListContainer) {
		console.error('未能找到ID为002的tbody元素，请检查HTML结构。');
		return;
	}

	// 清空现有内容
	courseListContainer.innerHTML = '';

	courses.forEach((course, index) => {
		const row = document.createElement('tr');
		row.innerHTML = `
            <td><input type="checkbox" class="course-checkbox"></td>
            <td>${index + 1}</td>
            <td>
                <div class="course-info">
                    <img src="${course.image_url || './default_course_image.png'}" alt="课程图片">
                    <span>${course.cname}<br>讲师：${course.tname}</span>
                </div>
            </td>
            <td>¥${parseFloat(course.cprice).toFixed(2)}</td>
            <td>${course.cstatus}</td>
            <td>${course.creleasetime || '未指定'}</td>
            <td>
                <a href="#" onclick="editCourse(${course.id})">编辑</a> |
                <a href="#" style="color: red;" onclick="deleteCourse(${course.id})">删除</a>
            </td>
        `;
		courseListContainer.appendChild(row);
	});
}

// 发送请求获取筛选后的课程列表
function fetchFilteredCourses(status) {
    console.log('正在按审核状态筛选:', status);
    const url = config.coursesip;
    let condition;
    
    switch(status.trim()) {
        case '待审核':
            condition = 'fA';
            break;
        case '已通过':
            condition = 'tA';
            break;
        case '已驳回':
            condition = 'eA';
            break;
        case '全部':
        default:
            condition = 'AA'; // 默认显示待审核的内容
            break;
    }

    // 确保 condition 不为空
    if (!condition) {
        console.error('未能映射状态到 condition:', status);
        return;
    }

    // 构建请求参数
    const params = new URLSearchParams({
        method: 'queryall',
        condition: condition
    });

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data && Array.isArray(data.data)) {
            console.log('筛选后的课程列表:', data.data);
            renderCourseTable(data.data);
        } else {
            console.error('无效的课程数据:', data);
            renderCourseTable([]);
        }
    })
    .catch(error => {
        console.error('获取筛选后的课程列表失败:', error);
        renderCourseTable([]);
    });
}

// 在状态下拉框变化时调用此函数
const statusSelect = document.getElementById('status');
if (statusSelect) {
    statusSelect.addEventListener('change', function() {
        fetchFilteredCourses(this.value);
    });
}

// 渲染课程列表
function renderCourses(courses) {
	const courseListContainer1 = document.getElementById('002');
	const courseListContainer = courseListContainer1.querySelector('tbody');
	const selectAllCheckbox = document.getElementById('selectAllCourses');

	if (!courseListContainer) {
		console.error('未能找到ID为002的tbody元素，请检查HTML结构。');
		return;
	}

	// 清空现有的课程列表
	courseListContainer.innerHTML = '';
	
	 // 如果没有搜索结果，显示提示信息
	if (courses.length === 0) {
		alert('没有找到符合条件的课程！');
		// 可以选择重置搜索条件
		document.getElementById('course-name').value = '';
		document.getElementById('status').value = '';
		document.getElementById('release-date').value = '';
		// 重新加载所有课程
		fetchAllCourses();
		return;
	}

	// 遍历课程数据并生成表格行
	courses.forEach((course, index) => {
		const row = document.createElement('tr');

		// 创建复选框单元格
		const checkboxCell = document.createElement('td');
		const checkbox = document.createElement('input');
		checkbox.type = 'checkbox';
		checkbox.className = 'course-checkbox';
		// 存储课程的id
		checkbox.dataset.courseId = course.id; 
		checkbox.addEventListener('change', updateSelectAll);
		checkboxCell.appendChild(checkbox);

		// 创建序号单元格
		const numberCell = document.createElement('td');
		numberCell.textContent = index + 1;

		// 创建课程信息单元格
		const courseInfoCell = document.createElement('td');
		const courseInfoDiv = document.createElement('div');
		courseInfoDiv.className = 'course-info';
		const courseImage = document.createElement('img');
		courseImage.src = course.image_url || './default_course_image.png';
		courseImage.alt = 'Course Image';
		const courseName = document.createElement('span');
		courseName.innerHTML = `${course.cname}<br>讲师：${course.tname}`;
		courseInfoDiv.appendChild(courseImage);
		courseInfoDiv.appendChild(courseName);
		courseInfoCell.appendChild(courseInfoDiv);

		// 创建其他单元格...
		const priceCell = document.createElement('td');
		priceCell.textContent = `¥${parseFloat(course.cprice).toFixed(2)}`;

		const statusCell = document.createElement('td');
		// statusCell.textContent = course.cstatus === '1' ? '已发布' : '未发布';
		statusCell.textContent = course.cstatus;

		const releaseDateCell = document.createElement('td');
		releaseDateCell.textContent = course.creleasetime || '未指定';

		const actionsCell = document.createElement('td');
		const editLink = document.createElement('a');
		editLink.href = '#';
		editLink.textContent = '编辑';
		const deleteLink = document.createElement('a');
		deleteLink.href = '#';
		deleteLink.style.color = 'red';
		deleteLink.textContent = '删除';
		actionsCell.appendChild(editLink);
		actionsCell.appendChild(document.createTextNode(' | '));
		actionsCell.appendChild(deleteLink);

		// 将所有单元格添加到行中
		row.appendChild(checkboxCell);
		row.appendChild(numberCell);
		row.appendChild(courseInfoCell);
		row.appendChild(priceCell);
		row.appendChild(statusCell);
		row.appendChild(releaseDateCell);
		row.appendChild(actionsCell);

		// 将行添加到表格中
		courseListContainer.appendChild(row);
	});

	// 添加全选复选框的事件监听器
	if (selectAllCheckbox) {
		selectAllCheckbox.addEventListener('change', function() {
			const checkboxes = document.querySelectorAll('.course-checkbox');
			checkboxes.forEach(checkbox => {
				checkbox.checked = this.checked;
			});
		});
	}
	
	if (selectAllCheckbox) {
		// 移除旧的事件监听器
		selectAllCheckbox.replaceWith(selectAllCheckbox.cloneNode(true));
		const newSelectAllCheckbox = document.getElementById('selectAllCourses');
		
		newSelectAllCheckbox.addEventListener('change', function() {
			const checkboxes = document.querySelectorAll('.course-checkbox');
			checkboxes.forEach(checkbox => {
				checkbox.checked = this.checked;
			});
			// 更新批量操作按钮状态
			updateSelectAll();
		});
	}

	// 更新总条数显示
	const totalCountElement = document.getElementById('totalCount');
	if (totalCountElement) {
		totalCountElement.textContent = courses.length;
	}

	// 处理分页大小变化
	const pageSizeSelect = document.getElementById('pageSizeSelect');
	if (pageSizeSelect) {
		pageSizeSelect.addEventListener('change', function() {
			const newPageSize = parseInt(this.value);
			// 重新渲染表格和分页
			updateTableDisplay(courses, newPageSize);
		});
	}
}

// 更新全选复选框状态的函数
function updateSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAllCourses');
    const checkboxes = document.querySelectorAll('.course-checkbox');
    const totalCheckboxes = checkboxes.length;
    const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
    
    // 更新全选框状态
    if (selectAllCheckbox) {
        if (checkedCount === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        } else if (checkedCount === totalCheckboxes) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        }
    }

    // 更新批量操作按钮显示状态（如果有的话）
    const batchOperationBtn = document.querySelector('.batch-operation');
    if (batchOperationBtn) {
        batchOperationBtn.style.display = checkedCount > 0 ? 'inline-block' : 'none';
    }
}

function updateTableDisplay(courses, pageSize) {
	const currentPage = 1; // 切换每页显示条数时，默认回到第一页
	const totalPages = Math.ceil(courses.length / pageSize);

	// 更新页码输入框的最大值
	const pageJumpInput = document.getElementById('pageJumpInput');
	if (pageJumpInput) {
		pageJumpInput.max = totalPages;

		// 添加跳转页码的事件监听
		pageJumpInput.addEventListener('keypress', function(e) {
			if (e.key === 'Enter') {
				const pageNum = parseInt(this.value);
				if (pageNum && pageNum > 0 && pageNum <= totalPages) {
					// 跳转到指定页码
					goToPage(pageNum, courses, pageSize);
				} else {
					alert('请输入有效的页码！');
					this.value = '';
				}
			}
		});
	}

	// 初始显示第一页数据
	goToPage(1, courses, pageSize);
}
// 跳转到指定页码
function goToPage(pageNum, courses, pageSize) {
	const start = (pageNum - 1) * pageSize;
	const end = start + pageSize;
	const currentPageData = courses.slice(start, end);
	// 重新渲染表格数据
	renderTableData(currentPageData);
	// 更新分页按钮
	updatePagination(Math.ceil(courses.length / pageSize), pageNum);
}

// 显示个人中心页面的js
// 修改显示个人中心页面的函数
function showPersonalCenter() {
    // 隐藏所有content-section
    document.querySelectorAll('.content-section').forEach(section => {
        section.style.display = 'none';
    });

    // 获取个人中心section
    const personalCenter = document.getElementById('personal-center');
    personalCenter.style.display = 'block';

    // 添加加载提示
    personalCenter.innerHTML = '<div class="loading">加载中...</div>';

    // 首先加载个人中心的HTML内容
    fetch('personalcenter.html')
        .then(response => response.text())
        .then(html => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const container = doc.querySelector('.container');

            if (!container) {
                throw new Error('未找到个人中心内容');
            }

            // 清除加载提示并添加内容
            personalCenter.innerHTML = '';
            personalCenter.appendChild(container);

            // 加载CSS
            if (!document.querySelector('link[href="css/personalcenter.css"]')) {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = 'css/personalcenter.css';
                document.head.appendChild(link);
            }

            // 获取用户数据并渲染
            fetch(`${config.usersip}?method=getuserinfo`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data && data.code === 200 && data.data) {
                    const userData = data.data;
                    // 更新头像
                    const avatar = personalCenter.querySelector('.avatar');
                    if (avatar) {
                        avatar.src = userData.avatar || './img/default-avatar.png';
                    }

                    // 更新基本信息
                    const infoItems = personalCenter.querySelectorAll('.info-item .value');
                    infoItems.forEach(item => {
                        const label = item.previousElementSibling.textContent;
                        switch(label) {
                            case '用户名称':
                                item.textContent = userData.username || 'N/A';
                                break;
                            case '手机号码':
                                item.textContent = userData.phone || 'N/A';
                                break;
                            case '用户邮箱':
                                item.textContent = userData.email || 'N/A';
                                break;
                            case '所属部门':
                                item.textContent = userData.department || 'N/A';
                                break;
                            case '所属角色':
                                item.textContent = userData.role || 'N/A';
                                break;
                        }
                    });

                    // 更新表单默认值
                    const basicInfoForm = personalCenter.querySelector('#basicInfoForm');
                    if (basicInfoForm) {
                        const inputs = basicInfoForm.querySelectorAll('input');
                        inputs.forEach(input => {
                            switch(input.type) {
                                case 'text':
                                    input.value = userData.username || '';
                                    break;
                                case 'tel':
                                    input.value = userData.phone || '';
                                    break;
                                case 'email':
                                    input.value = userData.email || '';
                                    break;
                                case 'radio':
                                    if (input.name === 'gender') {
                                        input.checked = input.value === userData.gender;
                                    }
                                    break;
                            }
                        });
                    }
                }
            })
            .catch(error => {
                console.error('获取用户数据失败:', error);
                personalCenter.querySelector('.info-card').innerHTML += `
                    <div class="error-message">
                        获取用户数据失败，请稍后重试
                        <button onclick="showPersonalCenter()">重试</button>
                    </div>
                `;
            });

            // 初始化个人中心功能
            initializePersonalCenter();
        })
        .catch(error => {
            console.error('加载个人中心内容失败:', error);
            personalCenter.innerHTML = `
                <div class="error-message">
                    加载个人中心失败，请稍后重试
                    <button onclick="showPersonalCenter()">重试</button>
                </div>
            `;
        });
}

// 初始化个人中心的事件监听
function initializePersonalCenter() {
	const personalCenter = document.getElementById('personal-center');
	const tabs = personalCenter.querySelectorAll('.tab');
	const forms = personalCenter.querySelectorAll('.info-form');

	tabs.forEach((tab, index) => {
		tab.addEventListener('click', () => {
			tabs.forEach(t => t.classList.remove('active'));
			forms.forEach(f => f.classList.remove('active'));

			tab.classList.add('active');
			forms[index].classList.add('active');
		});
	});
}

// 修改搜索表单的事件监听
document.addEventListener('DOMContentLoaded', function() {
    const searchForm1 = document.getElementById('002');
    const searchForm = searchForm1.querySelector('form');
    
    // 初始加载所有课程
    fetchAllCourses();

	// 修改搜索表单的事件监听
	if (searchForm) {
	    searchForm.addEventListener('submit', function(event) {
	        event.preventDefault();
	        const courseName = document.getElementById('course-name').value.trim();
	        const status = document.getElementById('status').value;
	        const releaseDate = document.getElementById('release-date').value;
	
	        // 调用统一的搜索函数
	        searchCourses(courseName, status, releaseDate);
	    });
	
	    // 添加重置按钮事件监听
	    const resetButton = searchForm.querySelector('button[type="reset"]');
	    if (resetButton) {
	        resetButton.addEventListener('click', function() {
	            // 清空日期输入框
	            const releaseDateInput = document.getElementById('release-date');
	            if (releaseDateInput) {
	                releaseDateInput.value = '';
	            }
	            // 重新加载所有课程
	            searchCourses('', '', '');
	        });
	    }
	}
});

// 搜索课程的函数   统一处理筛选的逻辑
function searchCourses(courseName, status, releaseDate,page = 1){
	console.log('搜索参数:', {
	        courseName,
	        status,
	        releaseDate,
	        page
	});
    const url = config.coursesip;
    const params = new URLSearchParams({
        method: 'queryall',
        cname: courseName || '',
        cstatus: status || '',
        releasedate: releaseDate || '',
        pageno: page.toString(),
        id: '123'
    });

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data && Array.isArray(data.data)) {
            renderCourseTable(data.data);
        } else {
            console.error('无效的搜索结果:', data);
            renderCourseTable([]);
        }
    })
    .catch(error => {
        console.error('搜索课程失败:', error);
        renderCourseTable([]);
    });
}

// 初始化教师审核页面
function initTeacherAudit() {
	const pageBtns = document.querySelectorAll('#s009 .page-btn');
	pageBtns.forEach(btn => {
		btn.addEventListener('click', () => {
			pageBtns.forEach(b => b.classList.remove('active'));
			btn.classList.add('active');
			// 这里可以添加分页逻辑
			console.log('切换到页码:', btn.textContent);
		});
	});

	const filterInput = document.querySelector('#s009 input[type="text"]');
	if (filterInput) {
		filterInput.addEventListener('input', () => {
			// 这里可以添加搜索逻辑
			console.log('搜索关键词:', filterInput.value);
		});
	}
}
// 打开课程预览
function openCoursePreview(courseId) {
    const modal = document.getElementById('coursePreviewModal');
    modal.style.display = 'flex';
    loadCoursePreviewData(courseId);
}

// 关闭课程预览
function closeCoursePreview() {
    const modal = document.getElementById('coursePreviewModal');
    modal.style.display = 'none';
}

// 加载课程预览数据
function loadCoursePreviewData(courseId) {
    const params = new URLSearchParams({
        method: 'queryone',
        id: courseId
    });

    fetch(`${config.coursesip}?${params}`)
        .then(response => response.json())
        .then(data => {
            console.log('服务器返回的课程预览数据:', data);
            if (data && data.code === 200 && data.data) {
                // 生成左侧菜单
                if (data.data.videourls) {
                    generatePreviewMenu(data.data.videourls);
                    
                    // 默认播放第一个视频
                    const firstVideo = Object.values(data.data.videourls)[0];
                    if (firstVideo) {
                        updatePreviewVideo(firstVideo);
                        // 选中第一个菜单项
                        const firstMenuItem = document.querySelector('.preview-content .chapter-title');
                        if (firstMenuItem) {
                            firstMenuItem.classList.add('active');
                        }
                    }
                }
                
                // 更新课程介绍内容
                updatePreviewIntro(data.data.cintroduce);
            }
        })
        .catch(error => {
            console.error('获取课程预览数据失败:', error);
        });
}

// 切换到预览模式
function switchToPreview() {
    // 获取当前课程ID
    const courseId = document.getElementById('detail-course-id').textContent;
    
    // 隐藏课程详情弹出层
    const detailModal = document.getElementById('courseDetailModal');
    detailModal.style.display = 'none';
    
    // 显示预览弹出层
    const previewModal = document.getElementById('coursePreviewModal');
    previewModal.style.display = 'flex';
    
    // 加载预览数据
    loadCoursePreviewData(courseId);
}

// 修改关闭预览的函数
function closeCoursePreview() {
    const previewModal = document.getElementById('coursePreviewModal');
    const detailModal = document.getElementById('courseDetailModal');
    
    previewModal.style.display = 'none';
    // 返回到详情页面
    detailModal.style.display = 'flex';
}

// 生成预览菜单
function generatePreviewMenu(videourls) {
    const courseMenu = document.querySelector('.preview-content .course-menu');
    courseMenu.innerHTML = '<div class="menu-title">课程目录</div>';
    
    Object.entries(videourls).forEach(([title, url], index) => {
        const menuItem = document.createElement('div');
        menuItem.className = 'chapter-title';
        menuItem.innerHTML = `
            <span class="section-number">${index + 1}.</span>
            <span class="section-title">${title}</span>
        `;
        
        menuItem.addEventListener('click', () => {
            document.querySelectorAll('.preview-content .chapter-title').forEach(item => {
                item.classList.remove('active');
            });
            menuItem.classList.add('active');
            updatePreviewVideo(url);
        });
        
        courseMenu.appendChild(menuItem);
    });
}


// 更新预览视频
function updatePreviewVideo(videoUrl) {
    const videoContainer = document.querySelector('.preview-content .video-container');
    if (videoContainer && videoUrl) {
        videoContainer.innerHTML = `
            <video 
                src="${videoUrl}" 
                controls
                style="width: 100%; height: 100%;"
            >
                您的浏览器不支持 video 标签
            </video>
        `;
    } else {
        videoContainer.innerHTML = '<div class="loading">暂无视频数据</div>';
    }
}

// 更新预览介绍
function updatePreviewIntro(introText) {
    const courseIntro = document.querySelector('.preview-content .course-intro');
    if (courseIntro) {
        courseIntro.innerHTML = `
            <h2>课程介绍</h2>
            <p>${introText || '暂无课程介绍'}</p>
        `;
    }
}

// 这是课程管理里面的分页和删除编辑的js
// 渲染课程表格
function renderCourseTable(data, currentPage = 1) {
	// 首先在控制台打印服务器返回的数据
	console.log('服务器返回的课程数据:', data);
	// 获取所有不重复的状态值并更新下拉框
	updateStatusDropdown(data);
    const tbody = document.getElementById('002').querySelector('tbody');
    tbody.innerHTML = '';
    
    const pageSize = 10; // 每页显示10条
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const pageData = data.slice(start, end);

    pageData.forEach((course, index) => {
        const row = document.createElement('tr');
       row.innerHTML = `
	   <td>${start + index + 1}</td>
	   <td>
		   <div class="course-info-container" style="display: flex; align-items: center; gap: 10px;">
			   <img src="${course.cover || './img/default-course.png'}" 
					alt="课程封面" 
					style="width: 60px; height: 40px; object-fit: cover; border-radius: 4px;">
			   <div class="course-text">
				   <div style="font-weight: bold;">${course.cname}</div>
				   <div style="font-size: 12px; color: #666;">讲师：${course.tname || '未知'}</div>
			   </div>
		   </div>
	   </td>
	   <td>${course.cprice || '免费'}</td>
	   <td>${course.cstatus}</td>
	   <td>${course.creleasetime || '未设置'}</td>
	   <td>
		   <button class="edit-btn" data-id="${course.id}">编辑</button>
		   <button class="delete-btn" data-id="${course.id}">删除</button>
	   </td>
               `;
        tbody.appendChild(row);
    });

    // 更新分页
    updatePagination(data.length, currentPage, pageSize);

    // 添加编辑和删除按钮的事件监听
    addButtonListeners();
}

// 修改更新状态下拉框的函数
function updateStatusDropdown(data) {
    const uniqueStatuses = [...new Set(data.map(course => course.cstatus))];
    console.log('课程状态列表:', uniqueStatuses);

    const statusSelect = document.getElementById('status');
    if (statusSelect) {
        const currentValue = statusSelect.value;
        
        statusSelect.innerHTML = '<option value="">全部状态</option>';
        
        uniqueStatuses.forEach(status => {
            if (status) {
                const option = document.createElement('option');
                option.value = status;
                option.textContent = status;
                statusSelect.appendChild(option);
            }
        });

        statusSelect.value = currentValue;

        // 移除旧的事件监听器
        statusSelect.removeEventListener('change', statusSelect.changeHandler);

        // 修改这里：使用 fetchFilteredCourses 替换 filterCoursesByStatus
        statusSelect.changeHandler = function() {
            console.log('状态选择变化:', this.value);
            fetchFilteredCourses(this.value);  // 使用正确的函数
        };
        
        statusSelect.addEventListener('change', statusSelect.changeHandler);
    }
}
// 新增状态筛选函数
function filterCoursesByStatus(status) {
    console.log('正在按状态筛选:', status);
    
    const url = config.coursesip;
    const params = new URLSearchParams({
        method: 'queryall',
        cstatus: status || '',
        pageno: '1',
        id: '123'
    });

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        console.log('状态筛选返回数据:', data);
        if (data && Array.isArray(data.data)) {
            renderCourseTable(data.data);
        } else {
            console.error('无效的筛选结果:', data);
            renderCourseTable([]);
        }
    })
    .catch(error => {
        console.error('状态筛选失败:', error);
        renderCourseTable([]);
    });
}
// 删除按钮的点击事件的函数
function addButtonListeners() {
    // 删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.dataset.id;
            if (confirm('确定要删除这个课程吗？')) {
                // 获取当前页面所有课程的 ID
                const allCourseIds = Array.from(document.querySelectorAll('.delete-btn'))
                    .map(button => button.dataset.id);

                // 发送删除请求，包含所有课程的 ID
                deleteCourse(courseId, allCourseIds);
            }
        });
    });

    // 编辑按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.dataset.id;
            editCourse(courseId);
        });
    });
}
// 删除课程
function deleteCourse(courseId) {
    const params = new URLSearchParams({
        method: 'delete',
        id: courseId
    });

    fetch(config.coursesip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('删除成功！');
            // 重新加载课程列表
            searchCourses('', '', '');
        } else {
            alert('删除失败：' + (data.msg || '未知错误'));
        }
    })
    .catch(error => {
        console.error('删除课程失败:', error);
        alert('删除失败，请稍后重试');
    });
}

// 编辑课程
function editCourse(courseId) {
    const params = new URLSearchParams({
        method: 'updatecourse',
        id: courseId
        // 添加其他需要更新的字段
    });

    fetch(config.coursesip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('编辑成功！');
            // 重新加载课程列表
            searchCourses('', '', '');
        } else {
            alert('编辑失败：' + (data.msg || '未知错误'));
        }
    })
    .catch(error => {
        console.error('编辑课程失败:', error);
        alert('编辑失败，请稍后重试');
    });
}

// 更新分页
// 更新分页UI
function updatePagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    const paginationDiv = document.querySelector('.pagination');
    paginationDiv.innerHTML = '';

    // 上一页
    const prevLink = document.createElement('a');
    prevLink.href = '#';
    prevLink.className = 'prev' + (currentPage === 1 ? ' disabled' : '');
    prevLink.textContent = '上一页';
    prevLink.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage > 1) {
            // 获取当前筛选条件
            const courseName = document.getElementById('course-name')?.value || '';
            const status = document.getElementById('status')?.value || '';
            const releaseDate = document.getElementById('release-date')?.value || '';
            // 请求上一页数据
            fetchPageData(currentPage - 1, pageSize, courseName, status, releaseDate);
        }
    });
    paginationDiv.appendChild(prevLink);

    // 页码
    for (let i = 1; i <= totalPages; i++) {
        const pageLink = document.createElement('a');
        pageLink.href = '#';
        pageLink.className = 'page' + (i === currentPage ? ' active' : '');
        pageLink.textContent = i;
        pageLink.addEventListener('click', (e) => {
            e.preventDefault();
            // 获取当前筛选条件
            const courseName = document.getElementById('course-name')?.value || '';
            const status = document.getElementById('status')?.value || '';
            const releaseDate = document.getElementById('release-date')?.value || '';
            // 请求指定页码数据
            fetchPageData(i, pageSize, courseName, status, releaseDate);
        });
        paginationDiv.appendChild(pageLink);
    }

    // 下一页
    const nextLink = document.createElement('a');
    nextLink.href = '#';
    nextLink.className = 'next' + (currentPage === totalPages ? ' disabled' : '');
    nextLink.textContent = '下一页';
    nextLink.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage < totalPages) {
            // 获取当前筛选条件
            const courseName = document.getElementById('course-name')?.value || '';
            const status = document.getElementById('status')?.value || '';
            const releaseDate = document.getElementById('release-date')?.value || '';
            // 请求下一页数据
            fetchPageData(currentPage + 1, pageSize, courseName, status, releaseDate);
        }
    });
    paginationDiv.appendChild(nextLink);
}

// 新增获取分页数据的函数
function fetchPageData(page, pageSize, courseName = '', status = '', releaseDate = '') {
    const params = new URLSearchParams({
        method: 'queryall',
        cname: courseName,
        cstatus: status,
        releasedate: releaseDate,
        pageno: page.toString(),
        pagesize: pageSize.toString(),
        id: '123'
    });

    fetch(config.coursesip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data && Array.isArray(data.data)) {
            renderCourseTable(data.data);
            updatePagination(data.total || data.data.length, page, pageSize);
        } else {
            console.error('无效的数据:', data);
            renderCourseTable([]);
        }
    })
    .catch(error => {
        console.error('获取数据失败:', error);
        renderCourseTable([]);
    });
}
// 渲染教师审核数据
function renderTeacherTable(teachers) {
    const teacherAuditContainer = document.querySelector('#s009 tbody');
    if (teacherAuditContainer) {
        const html = teachers.map((teacher, index) => `
            <tr>
                <td>${index + 1}</td>
                <td>${teacher.tname || ''}<br>${teacher.phone || ''}</td>
                <td>${teacher.direction || ''}</td>
                <td>${teacher.workyears || ''}年</td>
                <td>${formatDate(teacher.registrationTime) || ''}</td>
                <td><span class="status-tag pending">待审核</span></td>
                <td>
                    <button class="btn-info" onclick="showTeacherDetail('${teacher.id}')">查看详情</button>
                </td>
            </tr>
        `).join('');

        teacherAuditContainer.innerHTML = html;
    }
}

// 格式化日期函数
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}